<?php

namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Loader;

class Auth extends Common 
{	
	/**
	 * 权限列表
	 */
	public function index()
	{	
		
	}

	/**
	 * 添加权限
	 */
	public function add()
	{	
		if (Request::instance()->isPost()) {
			$username = input('post.username');
			$password = input('post.password');
			$email    = input('post.email');

			$validate = Loader::validate('Admin');
			$data     = ['username'=>$username, 'password'=>$password, 'email'=>$email];
			if (!$validate->scene('add')->check($data)) {
                return $this->error($validate->getError());
            }

			$value['username'] = $username;
			$value['password'] = md5($password);
			$value['email']    = $email;
			 
	  		$id = Db::name('admin')->insertGetId($value);

	  		if($id) {
	  			return $this->success('添加成功','/admin/admin/index');
	  		} else {
	  			return $this->error('添加失败');
	  		}	
		} else {
			return $this->fetch();
		}
		
	}

	/**
	 * 删除权限
	 */
	public function delete()
	{	
		$id = input('get.id');
		$num = DB::name('admin')->where('id', $id)->delete();
		if ($num) {
			return $this->success('删除成功');
		}else{
			return $this->error('删除失败');
		}
	}

	/**
	 * 编辑权限
	 */
	public function edit()
	{
		if (Request::instance()->isPost()) {
			$id   = input('get.id');
			$username = input('post.username');
			$password = input('post.password');
			$email    = input('post.email');

			$data['username'] = $username;
			$oldPassword = DB::name('admin')->where('id', $id)->value('password');
			if ($oldPassword != $password && $password != null) {
				$data['password'] = md5($password);
			}

			if ($email != NULL) {
				$data['email']    = $email;
			}

			$num = DB::name('admin')->where('id', $id)->update($data);
			if ($num) {
				return $this->success('更新成功', '/admin/admin/index');
			}else{
				return $this->error('更新失败');
			}
		}else{
			$id   = input('get.id');
			$info = DB::name('admin')->field('username, password, email')->where('id', $id)->find();
			$this->assign('id', $id);
			$this->assign('info', $info);
			return $this->fetch();
		}
	}	
}
